package com.chukun.search.services.impl;

import com.chukun.search.services.IQiniuFileUploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

@Service
public class QiniuFileUploadServiceImpl implements IQiniuFileUploadService, InitializingBean {
    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.Bucket}")
    private String bucket;

    private StringMap putPolicy;

    @Override
    public Response uploadFileToQiniuWithFile(File file) throws QiniuException {

        Response response = this.uploadManager.put(file, null, generatorFileUploadToken());
        int retry=0;
        while(response.needRetry() && retry++<3){
            response = this.uploadManager.put(file, null, generatorFileUploadToken());
        }
        return response;
    }

    @Override
    public Response uploadFileToQiniuWithStream(InputStream inputStream) throws QiniuException {
        Response response = this.uploadManager.put(inputStream, null, generatorFileUploadToken(),null,null);
        int retry=0;
        while(response.needRetry() && retry++<3){
            response = this.uploadManager.put(inputStream, null, generatorFileUploadToken(),null,null);
        }
        return response;
    }

    @Override
    public Response deleteFileInQiniu(String key) throws QiniuException {
        Response response = this.bucketManager.delete(bucket, key);
        int retry=0;
        while(response.needRetry() && retry++<3){
            response =  this.bucketManager.delete(bucket, key);
        }
        return response;
    }

    private String generatorFileUploadToken(){
        return this.auth.uploadToken(bucket,null,3600,putPolicy);
    }

    /**
     * 初始化putPolicy
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }
}
